package org.yuezejian.alarm.netty.channel.pool;

import com.alibaba.fastjson.JSON;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.yuezejian.alarm.netty.channel.UDPCustomChannelInitializer;
import org.yuezejian.alarm.netty.enums.ClientType;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * UDP通道池，用于管理和分配netty通道
 *
 * @author yuezejian
 * @since 2024.8.1
 */
@Slf4j
public class UDPChannelPool extends AbstractChannelPool {
    public UDPChannelPool(String host, int port, UDPCustomChannelInitializer initializer) {
        super(host, port, null, initializer, null);
        this.udpInitializer.setClientType(ClientType.UDP); // 设置协议类型为 UDP
    }

    @Override
    protected Channel createNewChannel() throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .handler(udpInitializer);
        log.info("UDP group:" + JSON.toJSONString(group));
        return bootstrap.connect(host, port).sync().channel();
    }
}
